package repository

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/forum/model"

	"github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// UserRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customUserRepository.
	UserRepository interface {
		FindOne(ctx context.Context, id uint64) (*model.ForumUser, error)
		FindOneWithExpire(
			ctx context.Context,
			id uint64,
			expire time.Duration,
		) (*model.ForumUser, error)
		FindOneNoCache(
			ctx context.Context,
			conn boil.ContextExecutor,
			id uint64,
		) (*model.ForumUser, error)
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumUser, int64, error) // ##24.11.15##
		Insert(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.ForumUser,
			rel *model.ForumUserRel,
		) error
		Update(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.ForumUser,
			rel *model.ForumUserRel,
		) error
		UpdateBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64, cols model.M) error
		SoftDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		Restore(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		ForceDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		ForceDeleteBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64) error

		GetMedia(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumAttachmentRelationship, int64, error) // ##24.11.16##

		InsertClickLog(
			ctx context.Context,
			tx boil.ContextExecutor,
			log *model.ForumUserClickLog,
		) error // ##24.12.24##
		GetClickLogs(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumUserClickLog, int64, error)
		InsertSearchLog(
			ctx context.Context,
			tx boil.ContextExecutor,
			log *model.ForumUserSearchLog,
		) error
		GetSearchLogs(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumUserSearchLog, int64, error)
		SetPageSetting(
			ctx context.Context,
			tx boil.ContextExecutor,
			key string,
			setting string,
		) (int64, error)
		GetPageSetting(
			ctx context.Context,
			tx boil.ContextExecutor,
			key string,
		) (string, error)
	}

	customUserRepository struct {
		modelx.CachedConn
		mysqlConn           *sql.DB
		cacheIdPrefix       string
		cacheIdExpirePrefix string
	}
)

// NewUserRepository returns a repository for the database table.
func NewUserRepository(mysqlConn *sql.DB, cacheConf cache.CacheConf) UserRepository {
	return &customUserRepository{
		CachedConn:          modelx.NewConn(mysqlConn, cacheConf),
		mysqlConn:           mysqlConn,
		cacheIdPrefix:       "cache:forum:users:id:",
		cacheIdExpirePrefix: "cache:forum:users:id:expire:",
	}
}

func (r *customUserRepository) FindOne(
	ctx context.Context,
	id uint64,
) (*model.ForumUser, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.ForumUser
	err := r.QueryCtx(ctx, &resp, cacheIdKey, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindForumUser(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.ForumUser) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customUserRepository) FindOneWithExpire(
	ctx context.Context,
	id uint64,
	expire time.Duration,
) (*model.ForumUser, error) {
	cacheIdKey := r.formatPrimaryWithExpire(id)
	var resp model.ForumUser
	err := r.QueryWithExpireCtx(ctx, &resp, cacheIdKey, expire, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindForumUser(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.ForumUser) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customUserRepository) FindOneNoCache(
	ctx context.Context,
	conn boil.ContextExecutor,
	id uint64,
) (*model.ForumUser, error) {
	var db boil.ContextExecutor = r.mysqlConn
	if conn != nil {
		db = conn
	}
	data, err := model.FindForumUser(ctx, db, id)
	logrus.Info(fmt.Sprintf("FindOneNoCache err: %+v", err))
	switch err {
	case nil:
		return data, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customUserRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumUser, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	var statistic bool
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumUserColumns.ID+" DESC"))
					mods = append(mods, model.ForumUserWhere.ID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumUserColumns.ID+" ASC"))
					mods = append(mods, model.ForumUserWhere.ID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		case "statistic":
			if val, ok := v.(string); ok && val == "1" { // 按 Status 统计
				statistic = true
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumUserColumns.ID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserColumns.ID, opMap)...)
		case model.ForumUserColumns.UserID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserColumns.UserID, opMap)...)
		case model.ForumUserColumns.UserNickname:
			mods = append(mods, modelx.GetStringMods(model.ForumUserColumns.UserNickname, opMap)...)
		case model.ForumUserColumns.UserAvatar:
			mods = append(mods, modelx.GetStringMods(model.ForumUserColumns.UserAvatar, opMap)...)
		case model.ForumUserColumns.UserEmail:
			mods = append(mods, modelx.GetStringMods(model.ForumUserColumns.UserEmail, opMap)...)
		case model.ForumUserColumns.UserURL:
			mods = append(mods, modelx.GetStringMods(model.ForumUserColumns.UserURL, opMap)...)
		case model.ForumUserColumns.UserStatus:
			mods = append(mods, modelx.GetIntMods(model.ForumUserColumns.UserStatus, opMap)...)
		case model.ForumUserColumns.Signature:
			mods = append(mods, modelx.GetStringMods(model.ForumUserColumns.Signature, opMap)...)
		case model.ForumUserColumns.CreatedBy:
			mods = append(mods, modelx.GetIntMods(model.ForumUserColumns.CreatedBy, opMap)...)
		case model.ForumUserColumns.CreatedAt:
			mods = append(mods, modelx.GetTimeMods(model.ForumUserColumns.CreatedAt, opMap)...)
		case model.ForumUserColumns.UpdatedAt:
			mods = append(mods, modelx.GetTimeMods(model.ForumUserColumns.UpdatedAt, opMap)...)
		case model.ForumUserColumns.DeletedAt:
			mods = append(mods, modelx.GetTimeMods(model.ForumUserColumns.DeletedAt, opMap)...)
		}
	}

	if statistic {
		mods = append(mods, qm.Select(fmt.Sprintf(
			"%s, count(%s) as %s",
			model.ForumUserColumns.UserStatus,
			model.ForumUserColumns.UserStatus,
			model.ForumUserColumns.CreatedBy,
		)))
		mods = append(mods, qm.GroupBy(model.ForumUserColumns.UserStatus))
		preList, preErr := model.ForumUsers(mods...).All(ctx, r.mysqlConn)
		if preErr != nil {
			err = preErr
			return
		}

		return preList, 0, nil
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumUsers(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.ForumUserColumns.ID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumUsers(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customUserRepository) Insert(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ForumUser,
	rel *model.ForumUserRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		err := data.Insert(ctx, db, boil.Infer())
		if err != nil {
			return err
		}

		if rel == nil {
			return nil
		}

		uid := data.ID
		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				v.ObjectID = uid
				v.ObjectType = uint16(globalkey.ForumAttachmentTypeAvatar)
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customUserRepository) Update(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ForumUser,
	rel *model.ForumUserRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		var uid uint64
		if data != nil {
			rowsAff, err := data.Update(ctx, db, boil.Blacklist(
				model.ForumUserColumns.ID,
				model.ForumUserColumns.CreatedAt,
				model.ForumUserColumns.DeletedAt,
			))
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotUpdated
			}

			uid = data.ID
		}

		if rel == nil {
			return nil
		}

		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				if v.AttachmentRelationshipID > 0 {
					_, err := v.Update(ctx, db, boil.Blacklist(
						model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID,
						model.ForumAttachmentRelationshipColumns.ObjectID,
						model.ForumAttachmentRelationshipColumns.ObjectType,
					))
					if err != nil {
						return err
					}
				} else {
					v.ObjectID = uid
					v.ObjectType = uint16(globalkey.ForumAttachmentTypeAvatar)
					err := v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.DelMediaIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.ForumAttachmentRelationshipWhere.AttachmentRelationshipID.IN(rel.DelMediaIds))
			_, err := model.ForumAttachmentRelationships(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customUserRepository) UpdateBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
	cols model.M,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.ForumUserWhere.ID.IN(ids))
			rowsAff, err := model.ForumUsers(mods...).UpdateAll(ctx, db, cols)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotUpdated
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customUserRepository) SoftDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.UserStatus == uint16(globalkey.StatusDeleted) {
		return nil
	}

	data.DelStatus = data.UserStatus
	data.UserStatus = uint16(globalkey.StatusDeleted)
	data.DeletedAt = null.TimeFrom(time.Now())

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.ForumUserColumns.DelStatus,
			model.ForumUserColumns.UserStatus,
			model.ForumUserColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customUserRepository) Restore(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.UserStatus != uint16(globalkey.StatusDeleted) {
		return nil
	}

	data.UserStatus = data.DelStatus
	data.DeletedAt = null.TimeFromPtr(nil)

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.ForumUserColumns.UserStatus,
			model.ForumUserColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customUserRepository) ForceDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Delete(ctx, db)
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotDeleted
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customUserRepository) ForceDeleteBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.ForumUserWhere.ID.IN(ids))

			rowsAff, err := model.ForumUsers(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotDeleted
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customUserRepository) getCacheKeys(data *model.ForumUser) []string {
	if data == nil {
		return []string{}
	}

	cacheIdKey := r.formatPrimary(data.ID)
	cacheIdExpireKey := r.formatPrimaryWithExpire(data.ID)
	cacheKeys := []string{
		cacheIdKey,
		cacheIdExpireKey,
	}

	return cacheKeys
}

func (r *customUserRepository) formatPrimary(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdPrefix, primary)
}

func (r *customUserRepository) formatPrimaryWithExpire(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdExpirePrefix, primary)
}

func (r *customUserRepository) formatPrimaries(primaries []uint64) []string {
	var resp []string
	for _, primary := range primaries {
		resp = append(resp, r.formatPrimary(primary))
		resp = append(resp, r.formatPrimaryWithExpire(primary))
	}

	return resp
}

func (r *customUserRepository) queryPrimary(ctx context.Context, conn *sql.DB, v any, primary any) error {
	var uid uint64
	if jsonId, ok := primary.(json.Number); ok {
		if int64Id, err := jsonId.Int64(); err == nil {
			uid = uint64(int64Id)
		} else {
			return err
		}
	}

	data, err := model.FindForumUser(ctx, conn, uid)
	if err != nil {
		return err
	}

	*v.(*model.ForumUser) = *data

	return nil
}

func (r *customUserRepository) GetMedia(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumAttachmentRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID+" DESC"))
					mods = append(mods, model.ForumAttachmentRelationshipWhere.AttachmentRelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID+" ASC"))
					mods = append(mods, model.ForumAttachmentRelationshipWhere.AttachmentRelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.ObjectID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.ObjectType, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentThumbnail:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentThumbnail, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentOrder:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentOrder, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentSource:
			mods = append(mods, modelx.GetStringMods(model.ForumAttachmentRelationshipColumns.AttachmentSource, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentImageURL:
			mods = append(mods, modelx.GetStringMods(model.ForumAttachmentRelationshipColumns.AttachmentImageURL, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentImageAlt:
			mods = append(mods, modelx.GetStringMods(model.ForumAttachmentRelationshipColumns.AttachmentImageAlt, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumAttachmentRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumAttachmentRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customUserRepository) InsertClickLog(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ForumUserClickLog,
) error {
	var db boil.ContextExecutor
	if tx != nil {
		db = tx
	} else {
		db = r.mysqlConn
	}

	return data.Insert(ctx, db, boil.Infer())
}

func (r *customUserRepository) GetClickLogs(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumUserClickLog, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	var oldest bool
	var latest bool
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumUserClickLogColumns.ClickLogID+" DESC"))
					mods = append(mods, model.ForumUserClickLogWhere.ClickLogID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumUserClickLogColumns.ClickLogID+" ASC"))
					mods = append(mods, model.ForumUserClickLogWhere.ClickLogID.GT(val))
					previousCount = 1
				}
			}
		case "orderBy":
			if withCount != 3 && withCount != 4 {
				if val, ok := v.(string); ok && val != "" {
					mods = append(mods, qm.OrderBy(val))
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && val != "" {
					selectCol = val
				}
			}
		case "oldest":
			if val, ok := v.(string); ok && val == "1" {
				oldest = true
			}
		case "latest":
			if val, ok := v.(string); ok && val == "1" {
				latest = true
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumUserClickLogColumns.ClickLogID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserClickLogColumns.ClickLogID, opMap)...)
		case model.ForumUserClickLogColumns.UserID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserClickLogColumns.UserID, opMap)...)
		case model.ForumUserClickLogColumns.PlatformID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserClickLogColumns.PlatformID, opMap)...)
		case model.ForumUserClickLogColumns.SearchLogID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserClickLogColumns.SearchLogID, opMap)...)
		case model.ForumUserClickLogColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserClickLogColumns.ObjectID, opMap)...)
		case model.ForumUserClickLogColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.ForumUserClickLogColumns.ObjectType, opMap)...)
		case model.ForumUserClickLogColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.ForumUserClickLogColumns.Status, opMap)...)
		}
	}

	if oldest || latest {
		if oldest {
			mods = append(mods, qm.Select(fmt.Sprintf(
				"min(%s) as %s",
				model.ForumUserClickLogColumns.ClickLogID,
				model.ForumUserClickLogColumns.ClickLogID,
			)))
		} else {
			mods = append(mods, qm.Select(fmt.Sprintf(
				"max(%s) as %s",
				model.ForumUserClickLogColumns.ClickLogID,
				model.ForumUserClickLogColumns.ClickLogID,
			)))
		}
		mods = append(mods, qm.GroupBy(model.ForumUserClickLogColumns.ObjectID))

		if withCount == 2 && limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}

		preList, listErr := model.ForumUserClickLogs(mods...).All(ctx, r.mysqlConn)
		if listErr != nil {
			err = listErr
			return
		}

		if len(preList) > 0 {
			if withCount >= 2 {
				if limit > 0 && len(preList) > limit {
					nextCount = 1
					preList = preList[:limit]
				}
				count = previousCount + nextCount*2
			}
			if len(preList) == 0 {
				return
			}

			oids := make([]uint64, 0, len(preList))
			for _, v := range preList {
				oids = append(oids, v.ObjectID)
			}
			var subMods []qm.QueryMod
			subMods = append(subMods, model.ForumUserClickLogWhere.ObjectID.IN(oids))
			var columns []string
			if selectCol != "" {
				if selectCol != "," {
					columns = strings.Split(selectCol, ",")
				}
				columns = append(columns, model.ForumUserClickLogColumns.ObjectID)
				columns = append(columns, model.ForumUserClickLogColumns.ObjectType)
			}
			if len(columns) > 0 {
				subMods = append(subMods, qm.Select(columns...))
			}
			list, err = model.ForumUserClickLogs(subMods...).All(ctx, r.mysqlConn)
			return
		}

		return
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumUserClickLogs(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}

		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	} else {
		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		} else {
			columns = append(columns, model.ForumUserClickLogColumns.ClickLogID)
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumUserClickLogs(mods...).All(ctx, r.mysqlConn)
	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customUserRepository) InsertSearchLog(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ForumUserSearchLog,
) error {
	var db boil.ContextExecutor
	if tx != nil {
		db = tx
	} else {
		db = r.mysqlConn
	}

	return data.Insert(ctx, db, boil.Infer())
}

func (r *customUserRepository) GetSearchLogs(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumUserSearchLog, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumUserSearchLogColumns.SearchLogID+" DESC"))
					mods = append(mods, model.ForumUserSearchLogWhere.SearchLogID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumUserSearchLogColumns.SearchLogID+" ASC"))
					mods = append(mods, model.ForumUserSearchLogWhere.SearchLogID.GT(val))
					previousCount = 1
				}
			}
		case "orderBy":
			if withCount != 3 && withCount != 4 {
				if val, ok := v.(string); ok && val != "" {
					mods = append(mods, qm.OrderBy(val))
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && val != "" {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumUserSearchLogColumns.SearchLogID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserSearchLogColumns.SearchLogID, opMap)...)
		case model.ForumUserSearchLogColumns.UserID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserSearchLogColumns.UserID, opMap)...)
		case model.ForumUserSearchLogColumns.PlatformID:
			mods = append(mods, modelx.GetIntMods(model.ForumUserSearchLogColumns.PlatformID, opMap)...)
		case model.ForumUserSearchLogColumns.Keyword:
			mods = append(mods, modelx.GetStringMods(model.ForumUserSearchLogColumns.Keyword, opMap)...)
		case model.ForumUserSearchLogColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.ForumUserSearchLogColumns.Status, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumUserSearchLogs(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}

		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	} else {
		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		} else {
			columns = append(columns, model.ForumUserSearchLogColumns.SearchLogID)
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumUserSearchLogs(mods...).All(ctx, r.mysqlConn)
	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customUserRepository) SetPageSetting(
	ctx context.Context,
	tx boil.ContextExecutor,
	key string,
	setting string,
) (rowsAff int64, err error) {
	var db boil.ContextExecutor
	if tx != nil {
		db = tx
	} else {
		db = r.mysqlConn
	}

	var mods []qm.QueryMod
	mods = append(mods, model.ForumForumMetumWhere.MetaKey.EQ(key))
	list, err := model.ForumForumMeta(mods...).All(ctx, db)
	if err != nil {
		return 0, err
	}

	if len(list) == 0 {
		if len(setting) > 0 {
			metum := &model.ForumForumMetum{
				ForumID:   1,
				MetaKey:   key,
				MetaValue: null.StringFrom(setting),
			}
			err = metum.Insert(ctx, db, boil.Infer())
		}

		return
	}

	metum := list[0]
	if len(setting) > 0 {
		metum.MetaValue = null.StringFrom(setting)
		rowsAff, err = metum.Update(ctx, db, boil.Blacklist(
			model.ForumForumMetumColumns.MetaID,
			model.ForumForumMetumColumns.ForumID,
			model.ForumForumMetumColumns.MetaKey,
		))
	} else {
		rowsAff, err = metum.Delete(ctx, db)
	}

	return
}

func (r *customUserRepository) GetPageSetting(
	ctx context.Context,
	tx boil.ContextExecutor,
	key string,
) (setting string, err error) {
	var db boil.ContextExecutor
	if tx != nil {
		db = tx
	} else {
		db = r.mysqlConn
	}

	var mods []qm.QueryMod
	mods = append(mods, model.ForumForumMetumWhere.MetaKey.EQ(key))
	list, err := model.ForumForumMeta(mods...).All(ctx, db)
	if err != nil {
		return "", err
	}

	if len(list) > 0 {
		if metum := list[0]; metum.MetaValue.Valid {
			setting = metum.MetaValue.String
		}
	}

	return
}
